@file:Suppress("OPT_IN_USAGE")

import kotlinx.browser.window
import kotlinx.dom.addClass
import org.w3c.dom.*
import org.w3c.xhr.FormData

//提交dialog中的表单, 参数是按钮
//<button ... onclick='client.dialogSubmit(this)'...>
@JsExport
@JsName("dialogSubmit")
fun dialogSubmit(e: Element) {
    val dlg = e.closest("div.modal") ?: return
    val form = dlg.query("form") as HTMLFormElement
    if (!form.checkValidity()) {
        form.addClass("was-validated")
        return
    }
    val formData = FormData(form)
    HttpPost(form.action).data(formData).requestJsonResult { jr ->
        if (jr.OK) {
            bootstrap.Modal.getInstance(dlg).hide()
            window.location.reload()
        } else {
            body.query("#dialogErrorMessage")?.textContent = jr.msg
        }
    }
}


//带有data-keys-name的a标签, 点击时, 携带选中的行的key参数, href="http://xxx.com/a"  => http://xx.com/a?keys=1,2,3
@JsExport
@JsName("appendTableCheckedValues")
fun appendTableCheckedValues(eid: String) {
    val ele: HTMLAnchorElement = findElementById(eid) as? HTMLAnchorElement ?: return
    ele.onclick = {
        val table: HTMLTableElement? = ele.nearest()
        val values: String = table?.dataCheckedValues ?: ""
        if (table == null || values.isEmpty()) {
            false
        } else {
            var url = ele.attr("href")!!
            val idx = url.indexOf('?')
            if (idx > 0) {
                url = url.substring(0, idx)
            }
            val keyName = ele.attr(DATA.KEY)!!
            ele.href = "$url?$keyName=$values"
            val cs = ele.attr(DATA.CONFIRM)
            cs == null || cs.isEmpty() || window.confirm(cs)
        }

    }
}

@JsExport
@JsName("checkAllRowsById")
fun checkAllRowsById(eid: String) {
    val cb: HTMLInputElement = findElementById(eid) as? HTMLInputElement ?: return
    val tb: HTMLTableElement = cb.closest("table") as? HTMLTableElement ?: return
    val ls: List<HTMLInputElement> = tb.all("td input[type='checkbox']")
    if (ls.isEmpty()) return
    cb.onSelf("click") { ele ->
        ls.forEach {
            it.checked = ele.checked
        }
        makeTableCheckedValues(tb)
    }
    ls.forEach {
        it.on("click") {
            makeTableCheckedValues(tb)
        }
    }
}

private var HTMLTableElement.dataCheckedValues: String
    get() = this.data("checked-values") ?: ""
    set(value) {
        this.data("checked-values", value)
    }

private fun makeTableCheckedValues(table: HTMLTableElement) {
    val ls = ArrayList<String>()
    table.all<HTMLInputElement>("td input[type='checkbox']").forEach { ele ->
        if (ele.checked) {
            ls += ele.value
        }
    }
    val s = ls.joinToString(",")
    table.dataCheckedValues = s
}

@JsExport
@JsName("bindUploadById")
fun bindUploadById(eid: String) {
    val div: HTMLDivElement = body.find("#$eid") ?: return
    UploadDiv(div)
}

@JsExport
@JsName("formOnSubmitById")
fun formOnSubmitById(eid: String) {
    val form: HTMLFormElement = body.find("#$eid") ?: return
    form.on("submit") { evt ->
        if (!form.checkValidity()) {
            evt.preventDefault()
            evt.stopPropagation()
        }
        form.addClass("was-validated")
    }
}

@JsExport
@JsName("showConfirmById")
fun showConfirmById(eid: String): Boolean {
    val e = body.query("#$eid") ?: return false
    val s = e.attr(DATA.CONFIRM)
    return s == null || s.isEmpty() || window.confirm(s)
}

@JsExport
@JsName("showDialogById")
fun showDialogById(eid: String): Boolean {
    val e = body.query("#$eid") ?: return false
    e.attr(DATA.MODAL) ?: return false
    val s = e.attr(DATA.CONFIRM)
    if (s == null || s.isEmpty() || window.confirm(s)) {
        openServerDialog(e)
    }
    return false
}

private fun openServerDialog(e: Element) {
    val attrOpen = e.attr(DATA.MODAL) ?: return
    val url = e.attr("href") ?: e.attr(DATA.URL) ?: return
    HttpGet(url).requestText { tv ->
        val m = body.div("modal fade") { tabIndex = -1 }
        m.htmlValue = tv
        m.on("hidden.bs.modal") {
            m.remove()
        }
        bsModal(m, attrOpen == "static").show()
    }

}

external fun invokeElementAttr(elem: HTMLElement, attr: String)

@JsExport
@JsName("evalElementAttr")
fun evalElementAttr(eid: String) {
    val e = body.query("#${eid}[${DATA.SCRIPT}]") ?: return
    val sc = e.attr(DATA.SCRIPT) ?: return
    if (sc.isNotEmpty()) {
        val c = e.attr(DATA.CONFIRM)
        if (c == null || c.isEmpty() || window.confirm(c)) {
            invokeElementAttr(e, DATA.SCRIPT)
        }
    }
}

@JsExport
@JsName("showLargeImageById")
fun showLargeImageById(eid: String): Boolean {
    val url = body.query("#$eid")?.data("src-large") ?: return false
    val dlg = bootDialog {
        largeSize()
        title("查看图片")
        modalBody.addClass("bg-secondary")
        container {
            div("text-center") {
                image("border border-info rounded") {
                    src = url
                }
            }

        }
    }
    dlg.show()
    return false
}
